package com.xbongbong.paas.service.dynamic.crm.strategy.impl;

import com.xbongbong.i18n.util.I18nMessageUtil;
import com.xbongbong.paas.constant.PaasConstant;
import com.xbongbong.paas.domain.entity.PaasFormDataEntity;
import com.xbongbong.paas.domain.entity.PaasFormEntity;
import com.xbongbong.paas.domain.entity.PaasStageEntity;
import com.xbongbong.paas.domain.entity.ext.PaasFormDataEntityExt;
import com.xbongbong.paas.enums.StageTypeEnum;
import com.xbongbong.paas.log.constant.CrmLogMemoConstant;
import com.xbongbong.paas.pojo.dto.CustomerMergeDTO;
import com.xbongbong.paas.pojo.dto.FormDataDeleteBatchDTO;
import com.xbongbong.paas.pojo.dto.FormDataUpdateDTO;
import com.xbongbong.paas.pojo.dto.SaasFormSaveDTO;
import com.xbongbong.paas.service.dynamic.crm.strategy.AbstractDynamicStrategy;
import com.xbongbong.paas.service.dynamic.crm.strategy.CustomerDynamicStrategy;
import com.xbongbong.paas.service.dynamic.crm.strategy.DecisionTreeDynamicStrategy;
import com.xbongbong.parent.interfaces.DynamicStrategy;
import com.xbongbong.paas.service.dynamic.crm.strategy.MainBusinessDynamicStrategy;
import com.xbongbong.paas.service.dynamic.crm.strategy.PushNotifyDynamicStrategy;
import com.xbongbong.paas.toolbox.util.StringUtil;
import com.xbongbong.pro.businesstage.pojo.dto.StageJumpDealDTO;
import com.xbongbong.pro.customercommunicate.pojo.dto.DynamicDTO;
import com.xbongbong.pro.dynamic.pojo.dto.DynamicArchiveDTO;
import com.xbongbong.pro.dynamic.pojo.dto.DynamicBackAndExitTeamDTO;
import com.xbongbong.pro.dynamic.pojo.dto.DynamicBackDTO;
import com.xbongbong.pro.dynamic.pojo.dto.DynamicCheckJoinTeamDTO;
import com.xbongbong.pro.dynamic.pojo.dto.DynamicDeleteDTO;
import com.xbongbong.pro.dynamic.pojo.dto.DynamicDistributeDTO;
import com.xbongbong.pro.dynamic.pojo.dto.DynamicGrapDTO;
import com.xbongbong.pro.dynamic.pojo.dto.DynamicLabelDTO;
import com.xbongbong.pro.dynamic.pojo.dto.DynamicMergeDTO;
import com.xbongbong.pro.dynamic.pojo.dto.DynamicRestoreDTO;
import com.xbongbong.pro.dynamic.pojo.dto.DynamicSaveDTO;
import com.xbongbong.pro.dynamic.pojo.dto.DynamicStageJumpDTO;
import com.xbongbong.pro.dynamic.pojo.dto.DynamicUpdateBatchDTO;
import com.xbongbong.pro.dynamic.pojo.dto.DynamicUpdateDTO;
import com.xbongbong.pro.formdata.pojo.vo.UpdateVO;
import com.xbongbong.pro.listbatch.pojo.dto.DistributionDTO;
import com.xbongbong.pro.listbatch.pojo.dto.ListBatchDTO;
import com.xbongbong.pro.opportunity.pojo.JudgeStageChangedPojo;
import com.xbongbong.saas.constant.BasicConstant;
import com.xbongbong.saas.constant.StringConstant;
import com.xbongbong.saas.domain.entity.CustomerUserEntity;
import com.xbongbong.saas.domain.entity.ext.CustomerEntityExt;
import com.xbongbong.saas.enums.ProjectLogEnum;
import com.xbongbong.saas.enums.XbbRefTypeEnum;
import com.xbongbong.saas.enums.business.CustomerManagementEnum;
import com.xbongbong.saas.enums.dictionary.DictionaryEnum;
import com.xbongbong.saas.enums.dictionary.PublicEnum;
import com.xbongbong.saas.model.CustomerModel;
import com.xbongbong.saas.model.DynamicModel;
import com.xbongbong.saas.service.DictionaryService;
import com.xbongbong.saas.toolbox.help.FastJsonHelper;
import com.xbongbong.sys.domain.entity.UserEntity;
import org.apache.commons.collections4.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 *客户动态实现
 *
 *@author weijianxun
 */
@Service("customerDynamicStrategyImpl")
public class CustomerDynamicStrategyImpl extends AbstractDynamicStrategy implements DynamicStrategy,
        CustomerDynamicStrategy, PushNotifyDynamicStrategy, DecisionTreeDynamicStrategy, MainBusinessDynamicStrategy {

    private final Logger LOG = LoggerFactory.getLogger(CustomerDynamicStrategyImpl.class);

//    private static final Map<String, Integer> refTextToLogTypeMap = new HashMap<>();
//    static {
//    }

    @Resource
    private DictionaryService dictionaryService;
    @Resource
    private CustomerModel customerModel;
    @Resource
    private DynamicModel dynamicModel;

    @Override
    public List<Integer> type() {
        return Arrays.asList(XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode());
    }

    @Override
    @Async("dynamicThreadPool")
    public void save(DynamicSaveDTO dynamicSaveDTO) {
        try {
            SaasFormSaveDTO saasFormSaveDTO = dynamicSaveDTO.getSaasFormSaveDTO();
            UserEntity creator = dynamicSaveDTO.getCreator();
            Long dataId = dynamicSaveDTO.getDataId();
            Long formId = dynamicSaveDTO.getFormId();
            PaasFormEntity paasForm = getPaasForm(saasFormSaveDTO.getCorpid(), formId, saasFormSaveDTO.getBusinessType());
            String communicateMemo;
            List<String> memoPlaceHolder;
            String isPublic = saasFormSaveDTO.getNewData().getString(CustomerManagementEnum.IS_PUBLIC.getAttr());
            String publicName = I18nMessageUtil.getMessage(Objects.equals(isPublic, String.valueOf(PublicEnum.PUBLIC.getCode())) ? PublicEnum.PUBLIC.getName() : paasForm.getName());
            String customerName = FastJsonHelper.getStringOrDefaultFromFormData(saasFormSaveDTO.getNewData(), CustomerManagementEnum.NAME.getAttr(), "");
            String stageCode = FastJsonHelper.getStringOrDefaultFromFormData(saasFormSaveDTO.getNewData(), CustomerManagementEnum.CUSTOMER_STAGE.getAttr(), "");
            JudgeStageChangedPojo judgeStageChangedPojo = dynamicSaveDTO.getJudgeStageChangedPojo();
            if (Objects.equals(saasFormSaveDTO.getIsImport(), BasicConstant.ONE)) {
                if (StringUtil.isNotEmpty(stageCode) && Objects.nonNull(judgeStageChangedPojo)) {
                    memoPlaceHolder = DynamicDTO.initMemoHolder(creator.getName(), publicName, judgeStageChangedPojo.getTargetStageName());
                    communicateMemo = CrmLogMemoConstant.DYNAMIC_USER_IMPORT_STAGE;
                } else {
                    memoPlaceHolder = DynamicDTO.initMemoHolder(creator.getName(), publicName, customerName);
                    communicateMemo = CrmLogMemoConstant.DYNAMIC_USER_IMPORT;
                }
            } else {
                if (StringUtil.isNotEmpty(stageCode) && Objects.nonNull(judgeStageChangedPojo)) {
                    memoPlaceHolder = DynamicDTO.initMemoHolder(creator.getName(), publicName, judgeStageChangedPojo.getTargetStageName());
                    communicateMemo = CrmLogMemoConstant.DYNAMIC_USER_ADD_STAGE;
                } else {
                    memoPlaceHolder = DynamicDTO.initMemoHolder(creator.getName(), publicName, customerName);
                    communicateMemo = CrmLogMemoConstant.DYNAMIC_USER_ADD;
                }
            }
            DynamicDTO dynamicDTO = initDynamicDTO(creator.getUserId(), communicateMemo, ProjectLogEnum.CUSTOMER_CREATE.getSubType(), memoPlaceHolder, paasForm, paasForm.getSaasMark(), dataId);
            insertDynamic(Collections.singletonList(dynamicDTO), saasFormSaveDTO.getCorpid());
        } catch (Exception e) {
            LOG.error("com.xbongbong.paas.service.dynamic.crm.strategy.impl.CustomerDynamicStrategyImpl.save", e);
        }
    }

    @Override
    @Async("dynamicThreadPool")
    public void update(DynamicUpdateDTO dynamicUpdateDTO) {
        try {
            FormDataUpdateDTO formDataUpdateDTO = dynamicUpdateDTO.getFormDataUpdateDTO();
            PaasFormDataEntity paasFormDataEntity = dynamicUpdateDTO.getBeforeUpdateVO().getPaasFormDataEntity();
            UpdateVO updateVO = dynamicUpdateDTO.getUpdateVO();
            PaasFormEntity paasForm = getPaasForm(formDataUpdateDTO.getCorpid(), paasFormDataEntity.getFormId(), formDataUpdateDTO.getBusinessType());

            DynamicDTO dynamicDTO = initDynamicDTO(updateVO.getUserVO().getUserId(), CrmLogMemoConstant.DYNAMIC_USER_UPDATE_BASE_INFO, ProjectLogEnum.CUSTOMER_UPDATE.getSubType(),
                    DynamicDTO.initMemoHolder(updateVO.getUserVO().getName(), paasForm.getName()), paasForm, formDataUpdateDTO.getSaasMark(), paasFormDataEntity.getId());
            insertDynamic(Collections.singletonList(dynamicDTO), formDataUpdateDTO.getCorpid());
        } catch (Exception e) {
            LOG.error("com.xbongbong.paas.service.dynamic.crm.strategy.impl.CustomerDynamicStrategyImpl.update", e);
        }
    }

    @Override
    @Async("dynamicThreadPool")
    public void batchUpdate(DynamicUpdateBatchDTO dynamicUpdateBatchDTO) {
        try {
            super.batchUpdate(dynamicUpdateBatchDTO, ProjectLogEnum.CUSTOMER_UPDATE.getSubType());
        } catch (Exception e) {
            LOG.error("com.xbongbong.paas.service.dynamic.crm.strategy.impl.CustomerDynamicStrategyImpl.batchUpdate", e);
        }
    }

    @Override
    @Async("dynamicThreadPool")
    public void batchDelete(DynamicDeleteDTO dynamicDeleteDTO) {
        try {
            List<Long> allowDeleteDataIds = dynamicDeleteDTO.getAllowDeleteDataIds();
            FormDataDeleteBatchDTO formDataDeleteBatchDTO = dynamicDeleteDTO.getFormDataDeleteBatchDTO();
            List<DynamicDTO> dynamicCustomerDTOS = new ArrayList<>(allowDeleteDataIds.size());
            PaasFormEntity paasForm = getPaasForm(formDataDeleteBatchDTO.getCorpid(), formDataDeleteBatchDTO.getFormId(), formDataDeleteBatchDTO.getBusinessType());
            List<String> memoPlaceHolder = DynamicDTO.initMemoHolder(formDataDeleteBatchDTO.getLoginUserName(), paasForm.getName());
            for (Long deleteCustomerId : allowDeleteDataIds) {
                DynamicDTO dynamicDTO = initDynamicDTO(formDataDeleteBatchDTO.getUserId(), CrmLogMemoConstant.DYNAMIC_USER_DELETE, ProjectLogEnum.CUSTOMER_DELETE.getSubType(),
                        memoPlaceHolder, paasForm, formDataDeleteBatchDTO.getSaasMark(), deleteCustomerId);
                dynamicCustomerDTOS.add(dynamicDTO);
            }
            insertDynamic(dynamicCustomerDTOS, formDataDeleteBatchDTO.getCorpid());
        } catch (Exception e) {
            LOG.error("com.xbongbong.paas.service.dynamic.crm.strategy.impl.CustomerDynamicStrategyImpl.batchDelete", e);
        }
    }

    @Override
    @Async("dynamicThreadPool")
    public void grap(DynamicGrapDTO dynamicGrapDTO) {
        try {
            List<Long> finalCustomerIdList = dynamicGrapDTO.getAllowGrapDtatIds();
            ListBatchDTO listBatchDTO = dynamicGrapDTO.getListBatchDTO();
            UserEntity userEntity = dynamicGrapDTO.getUserEntity();
            List<DynamicDTO> dynamicCustomerDTOS = new ArrayList<>(finalCustomerIdList.size());
            String corpid = listBatchDTO.getCorpid();
            Long formId = listBatchDTO.getFormId();
            PaasFormEntity paasForm = getPaasForm(corpid, formId, listBatchDTO.getBusinessType());
            List<String> memoHolder;
            if (Objects.isNull(formId)) {
                memoHolder = DynamicDTO.initMemoHolder(userEntity.getName(), XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getName());
            } else {
                memoHolder = DynamicDTO.initMemoHolder(userEntity.getName(), paasForm.getName());
            }
            for (Long customerId : finalCustomerIdList) {
                DynamicDTO dynamicDTO = initDynamicDTO(userEntity.getUserId(), CrmLogMemoConstant.DYNAMIC_USER_GRAP, ProjectLogEnum.CUSTOMER_GRAB.getSubType(), memoHolder,
                        paasForm, listBatchDTO.getSaasMark(), customerId);
                dynamicCustomerDTOS.add(dynamicDTO);
            }
            insertDynamic(dynamicCustomerDTOS, corpid);
        } catch (Exception e) {
            LOG.error("com.xbongbong.paas.service.dynamic.crm.strategy.impl.CustomerDynamicStrategyImpl.grap", e);
        }
    }

    @Override
    @Async("dynamicThreadPool")
    public void back(DynamicBackDTO dynamicBackDTO) {
        try {
            ListBatchDTO listBatchDTO = dynamicBackDTO.getListBatchDTO();
            List<Long> allowBackDataIds = dynamicBackDTO.getAllowBackDataIds();
            if(CollectionUtils.isNotEmpty(allowBackDataIds)) {
                Map<String, Object> params = new HashMap<>();
                params.put(StringConstant.IDIN, allowBackDataIds);
                params.put(StringConstant.COLUMNS,"id , data");
                List<CustomerEntityExt> customerEntityExts = customerModel.findEntitysWithoutSub(params);
                Map<Long, CustomerEntityExt> customerIdToEntityMap = customerEntityExts.stream().collect(Collectors.toMap(CustomerEntityExt::getId, item -> item));                String corpid = listBatchDTO.getCorpid();
                Long formId = listBatchDTO.getFormId();
                List<DynamicDTO> dynamicCustomerDTOList = new ArrayList<>();
                PaasFormEntity paasForm = getPaasForm(corpid, formId, listBatchDTO.getBusinessType());
                List<String> memoHolder = DynamicDTO.initMemoHolder(listBatchDTO.getLoginUserName(), paasForm.getName());
                for (Long customerId : allowBackDataIds) {
                    CustomerEntityExt customerEntityExt = customerIdToEntityMap.get(customerId);
                    if (Objects.nonNull(customerEntityExt) && Objects.equals(customerEntityExt.getData().getInteger(CustomerManagementEnum.IS_PUBLIC.getAttr()),BasicConstant.ONE)) {
                        DynamicDTO dynamicDTO = initDynamicDTO(listBatchDTO.getUserId(), CrmLogMemoConstant.DYNAMIC_USER_BACK, ProjectLogEnum.CUSTOMER_BACK.getSubType(), memoHolder,
                                paasForm, listBatchDTO.getSaasMark(), customerId);
                        dynamicCustomerDTOList.add(dynamicDTO);
                    }
                }
                insertDynamic(dynamicCustomerDTOList, corpid);
            }
        } catch (Exception e) {
            LOG.error("com.xbongbong.paas.service.dynamic.crm.strategy.impl.CustomerDynamicStrategyImpl.back", e);
        }
    }

    @Override
    @Async("dynamicThreadPool")
    public void backAndExitTeam(DynamicBackAndExitTeamDTO dynamicBackAndExitTeamDTO) {
        try {
            List<DynamicDTO> dynamicDTOS = new ArrayList<>(dynamicBackAndExitTeamDTO.getCustomerIds().size());
            UserEntity creator = dynamicBackAndExitTeamDTO.getCreator();
            Map<Long, StringBuffer> customerIdToUserNameMap = dynamicBackAndExitTeamDTO.getCustomerIdToUserNameMap();
            for (Long customerId : dynamicBackAndExitTeamDTO.getCustomerIds()) {
                StringBuffer userName = customerIdToUserNameMap.get(customerId);
                if (Objects.nonNull(userName) && !Objects.equals(creator.getName(), userName.toString())) {
                    DynamicDTO dynamicDTO = initDynamicDTO(creator.getUserId(), CrmLogMemoConstant.DYNAMIC_USER_BACK_EXIT_TEAM, ProjectLogEnum.CUSTOMER_BACK.getSubType(),
                            DynamicDTO.initMemoHolder(creator.getName(), userName.toString()), null, null, customerId);
                    dynamicDTOS.add(dynamicDTO);
                }
                DynamicDTO dynamicdto = initDynamicDTO(creator.getUserId(), CrmLogMemoConstant.DYNAMIC_USER_OWN_BACK_EXIT_TEAM, ProjectLogEnum.CUSTOMER_BACK.getSubType(),
                        DynamicDTO.initMemoHolder(creator.getName()), null, null, customerId);
                dynamicDTOS.add(dynamicdto);
            }
            insertDynamic(dynamicDTOS, dynamicBackAndExitTeamDTO.getCorpid());
        } catch (Exception e) {
            LOG.error("com.xbongbong.paas.service.dynamic.crm.strategy.impl.CustomerDynamicStrategyImpl.backAndExitTeam", e);
        }
    }

    @Override
    @Async("dynamicThreadPool")
    public void scriptBackAndExitTeam(DynamicBackAndExitTeamDTO dynamicBackAndExitTeamDTO) {
        try {
            backAndExitTeam(dynamicBackAndExitTeamDTO, CrmLogMemoConstant.DYNAMIC_USER_BACK_EXIT_TEAM_SCRIPT, ProjectLogEnum.CUSTOMER_BACK.getSubType());
        } catch (Exception e) {
            LOG.error("com.xbongbong.paas.service.dynamic.crm.strategy.impl.CustomerDynamicStrategyImpl.scriptBackAndExitTeam", e);
        }
    }

    @Override
    @Async("dynamicThreadPool")
    public void leaveBackAndExitTeam(DynamicBackAndExitTeamDTO dynamicBackAndExitTeamDTO) {
        try {
            backAndExitTeam(dynamicBackAndExitTeamDTO, CrmLogMemoConstant.DYNAMIC_USER_BACK_EXIT_TEAM_LEAVE, ProjectLogEnum.CUSTOMER_EXIT_TEAM.getSubType());
        } catch (Exception e) {
            LOG.error("com.xbongbong.paas.service.dynamic.crm.strategy.impl.CustomerDynamicStrategyImpl.leaveBackAndExitTeam", e);
        }
    }

    private void backAndExitTeam(DynamicBackAndExitTeamDTO dynamicBackAndExitTeamDTO, String memo, Integer logType) {
        Map<Long, List<CustomerUserEntity>> customerIdToUserMap = dynamicBackAndExitTeamDTO.getCustomerIdToUserMap();
        UserEntity creator = dynamicBackAndExitTeamDTO.getCreator();
        List<DynamicDTO> dynamicDTOS = new ArrayList<>(dynamicBackAndExitTeamDTO.getCustomerIds().size());
        for (Long customerId : dynamicBackAndExitTeamDTO.getCustomerIds()) {
            List<CustomerUserEntity> customerUserEntities = customerIdToUserMap.get(customerId);
            if (CollectionUtils.isNotEmpty(customerUserEntities)) {
                for (CustomerUserEntity customerUserEntity : customerUserEntities) {
                    DynamicDTO dynamicDTO = initDynamicDTO(creator.getUserId(), memo, logType,
                            DynamicDTO.initMemoHolder(customerUserEntity.getUserName()), null, null, customerId);
                    dynamicDTOS.add(dynamicDTO);
                }
            }
        }
        insertDynamic(dynamicDTOS, dynamicBackAndExitTeamDTO.getCorpid());
    }

    @Override
    @Async("dynamicThreadPool")
    public void checkJoinTeam(DynamicCheckJoinTeamDTO dynamicCheckJoinTeamDTO) {
        try {
            super.checkJoinTeam(dynamicCheckJoinTeamDTO, ProjectLogEnum.CUSTOMER_TEAM_ADD.getSubType());
        } catch (Exception e) {
            LOG.error("com.xbongbong.paas.service.dynamic.crm.strategy.impl.CustomerDynamicStrategyImpl.checkJoinTeam", e);
        }
    }

    @Override
    @Async("dynamicThreadPool")
    public void restore(DynamicRestoreDTO dynamicRestoreDTO) {
        try {
            ListBatchDTO listBatchDTO = dynamicRestoreDTO.getListBatchDTO();
            List<Long> allowDataIds = dynamicRestoreDTO.getAllowDataIds();
            Long formId = listBatchDTO.getFormId();
            String corpid = listBatchDTO.getCorpid();
            List<DynamicDTO> dynamicCustomerDTOS = new ArrayList<>(allowDataIds.size());
            PaasFormEntity paasForm = getPaasForm(corpid, formId, listBatchDTO.getBusinessType());
            List<String> memoHolder = DynamicDTO.initMemoHolder(listBatchDTO.getLoginUserName(), paasForm.getName());
            for (Long customerId : allowDataIds) {
                DynamicDTO dynamicDTO = initDynamicDTO(listBatchDTO.getUserId(), CrmLogMemoConstant.DYNAMIC_USER_RESTORE, ProjectLogEnum.CUSTOMER_RESTORE.getSubType(), memoHolder,
                        paasForm, listBatchDTO.getSaasMark(), customerId);
                dynamicCustomerDTOS.add(dynamicDTO);
            }
            insertDynamic(dynamicCustomerDTOS, corpid);
        } catch (Exception e) {
            LOG.error("com.xbongbong.paas.service.dynamic.crm.strategy.impl.CustomerDynamicStrategyImpl.restore", e);
        }
    }

    @Override
    @Async("dynamicThreadPool")
    public void merge(DynamicMergeDTO dynamicMergeDTO) {
        try {
            CustomerMergeDTO customerMergeDTO = dynamicMergeDTO.getCustomerMergeDTO();
            CustomerEntityExt updateEntity = dynamicMergeDTO.getUpdateEntity();
            CustomerEntityExt delEntity = dynamicMergeDTO.getDelEntity();
            String corpid = customerMergeDTO.getCorpid();
            Long formId = customerMergeDTO.getFormId();
            PaasFormEntity paasForm = getPaasForm(corpid, formId, customerMergeDTO.getBusinessType());
            DynamicDTO dynamicDTO = initDynamicDTO(customerMergeDTO.getUserId(), CrmLogMemoConstant.DYNAMIC_MERGE_CUSTOMER, ProjectLogEnum.CUSTOMER_MERGE.getSubType(),
                    DynamicDTO.initMemoHolder(customerMergeDTO.getLoginUserName(), updateEntity.getData().getString(CustomerManagementEnum.NAME.getAttr()), delEntity.getData().getString(CustomerManagementEnum.NAME.getAttr())),
                    paasForm, null, updateEntity.getId());
            insertDynamic(Collections.singletonList(dynamicDTO), corpid);

            Map<String, Object> params = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            params.put(StringConstant.CORPID, corpid);
            params.put("customerId", delEntity.getId());
            params.put("updateCustomerId", updateEntity.getId());
            // 迁移跟进记录的动态
            params.put("logType", 0);
            dynamicModel.updateData(params);
        } catch (Exception e) {
            LOG.error("com.xbongbong.paas.service.dynamic.crm.strategy.impl.CustomerDynamicStrategyImpl.merge", e);
        }
    }

    @Override
    @Async("dynamicThreadPool")
    public void archive(DynamicArchiveDTO dynamicArchiveDTO) {
        try {
            super.archive(dynamicArchiveDTO, ProjectLogEnum.CUSTOMER_ARCHIVE.getSubType());
        } catch (Exception e) {
            LOG.error("com.xbongbong.paas.service.dynamic.crm.strategy.impl.CustomerDynamicStrategyImpl.archive", e);
        }
    }

    @Override
    @Async("dynamicThreadPool")
    public void distribute(DynamicDistributeDTO dynamicDistributeDTO) {
        try {
            List<Long> customerIds = dynamicDistributeDTO.getAllowDataIds();
            DistributionDTO distributionDTO = dynamicDistributeDTO.getDistributionDTO();
            UserEntity userEntity = dynamicDistributeDTO.getUserEntity();
            String corpid = distributionDTO.getCorpid();

            List<DynamicDTO> dynamicCustomerDTOList = new ArrayList<>(customerIds.size());
            PaasFormEntity paasForm = getPaasForm(corpid, distributionDTO.getFormId(), distributionDTO.getBusinessType());

            // Boolean isPublic = Objects.equals(XbbRefTypeEnum.CUSTOMER_PUBLIC.getCode(),distributionDTO.getSubBusinessType());
            // String customerPosition = I18nMessageUtil.getMessage(I18nStringConstant.CUSTOMER_LIST);
            // String distributeTag = I18nMessageUtil.getMessage(I18nStringConstant.CUSTOMER_ALLOCATION);
            // if (isPublic) {
            //     customerPosition = I18nMessageUtil.getMessage(I18nStringConstant.HIGH_SEAS);
            //     distributeTag = I18nMessageUtil.getMessage(I18nStringConstant.HIGH_SEAS_DISTRIBUTION);
            // }

            List<String> memoHolder = DynamicDTO.initMemoHolder(distributionDTO.getLoginUserName(), paasForm.getName(), userEntity.getName());
            for (Long customerId : customerIds) {
                DynamicDTO dynamicDTO = initDynamicDTO(distributionDTO.getUserId(), CrmLogMemoConstant.DYNAMIC_USER_DISTRIBUTE, ProjectLogEnum.CUSTOMER_DISTRIBUTE.getSubType(),
                        memoHolder, paasForm, distributionDTO.getSaasMark(), customerId);
                dynamicCustomerDTOList.add(dynamicDTO);
            }
            insertDynamic(dynamicCustomerDTOList, corpid);
        } catch (Exception e) {
            LOG.error("com.xbongbong.paas.service.dynamic.crm.strategy.impl.CustomerDynamicStrategyImpl.distribute", e);
        }
    }

    @Override
    @Async("dynamicThreadPool")
    public void stageJump(DynamicStageJumpDTO dynamicStageJumpDTO) {
        try {
            StageJumpDealDTO stageJumpDealDTO = dynamicStageJumpDTO.getStageJumpDealDTO();
            String corpid = stageJumpDealDTO.getCorpid();
            String memo = dynamicStageJumpDTO.getMemo();
            PaasFormDataEntityExt paasFormDataEntityExt = dynamicStageJumpDTO.getPaasFormDataEntityExt();
            Long customerId = paasFormDataEntityExt.getDataId();
            Long formId = stageJumpDealDTO.getFormId();

            PaasStageEntity toStageEntity = stageJumpDealDTO.getToStageEntity();
            Integer stageType = toStageEntity.getType();
            PaasStageEntity fromStageEntity = stageJumpDealDTO.getFromStageEntity();
            String nowStageName = fromStageEntity == null ? "开始阶段" : fromStageEntity.getName();
            String stageName = toStageEntity.getName();

            PaasFormEntity paasForm = getPaasForm(corpid, stageJumpDealDTO.getFormId(), stageJumpDealDTO.getBusinessType());
            if (StringUtil.isEmpty(memo)) {
                if (Objects.equals(stageType, StageTypeEnum.FAIL_STAGE.getType())) {
                    //流失
                    Map<String, String> wastageReasonMap = dictionaryService.getDictionaryMap(DictionaryEnum.CUSTOMER_STAGE_WASTAGE, corpid, formId);
                    String wastageReason = wastageReasonMap.get(stageJumpDealDTO.getReasonId().toString());
                    memo = String.format(I18nMessageUtil.getMessage(CrmLogMemoConstant.DYNAMIC_USER_STAGE), stageJumpDealDTO.getLoginUserName(), paasForm.getName(), nowStageName, stageName);
                    if (!StringUtil.isEmpty(wastageReason)) {
                        memo += "，" + CustomerManagementEnum.WASTAGE.getAttrName() + "：" + wastageReason;
                    }
                    memo += "；" + stageJumpDealDTO.getMemo();
                } else {
                    memo = String.format(I18nMessageUtil.getMessage(CrmLogMemoConstant.DYNAMIC_USER_STAGE), stageJumpDealDTO.getLoginUserName(), paasForm.getName(), nowStageName, stageName);
                }
            }
            DynamicDTO dynamicDTO = initDynamicDTO(stageJumpDealDTO.getUserId(), memo, ProjectLogEnum.CUSTOMER_STAGE.getSubType(), null,
                    paasForm, stageJumpDealDTO.getSaasMark(), customerId);
            insertDynamic(Collections.singletonList(dynamicDTO), corpid);
        } catch (Exception e) {
            LOG.error("com.xbongbong.paas.service.dynamic.crm.strategy.impl.CustomerDynamicStrategyImpl.stageJump", e);
        }
    }

    @Override
    @Async("dynamicThreadPool")
    public void label(DynamicLabelDTO dynamicLabelDTO) {
        try {
            super.label(dynamicLabelDTO, ProjectLogEnum.CUSTOMER_UPDATE.getSubType());
        } catch (Exception e) {
            LOG.error("com.xbongbong.paas.service.dynamic.crm.strategy.impl.CustomerDynamicStrategyImpl.label", e);
        }
    }
}
